package com.millioncool.selfpagingsimple.paging;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.millioncool.selfpagingsimple.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: QDL
 * @CreateDate: 2021/4/26 15:00
 */
public abstract class BasePagingListAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Context context;
    LayoutInflater layoutInflater;
    private PagingPager<T> pagingPager;
    List<T> lists = new ArrayList<>();

    public BasePagingListAdapter(Context context) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    public synchronized void submitList(List<T> pagingLiveData, final PagingPager<T> pagingPager) {
        this.pagingPager = pagingPager;
        new Handler(Looper.getMainLooper()).post(() -> {
            if (pagingPager.isRefresh) {
                lists.clear();
            }
            lists.addAll(pagingLiveData);
            notifyDataSetChanged();
        });
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == LoadMoreViewHolder.TYPE_ITEM) {
            return new LoadMoreViewHolder(layoutInflater.inflate(R.layout.load_more_view, parent, false));
        }
        return onCreateViewHolder(parent, viewType, pagingPager.getCurrentState());
    }


    public abstract VH onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType, final LoadState loadState);

    public abstract void onBindViewHolder(@NonNull final VH holder, final int position, final LoadState loadState);

    @Override
    public int getItemViewType(int position) {
        if (position == lists.size()) {
            return LoadMoreViewHolder.TYPE_ITEM;
        }
        return getPagingItemViewType(position);
    }

    public abstract int getPagingItemViewType(int position);

    public T getItem(int position) {
        if (lists.size() - position == 4) {
            pagingPager.listener.loadData();
        }
        if (position < lists.size()) {
            return lists.get(position);
        }

        return null;
    }

    @Override
    public int getItemCount() {
        return lists.size() + 1;
    }

    public static class LoadMoreViewHolder extends RecyclerView.ViewHolder {
        public final static int TYPE_ITEM = -99;

        public LoadMoreViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}